package me.zhengjie.utils;

import cn.hutool.core.util.RandomUtil;
import org.apache.commons.lang3.RandomStringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class OrderNoUtils {
    private OrderNoUtils(){}
    private static class OrderNoUtilsHolder {
        private static final OrderNoUtils INSTANCE = new OrderNoUtils();
    }

    public static final OrderNoUtils getInstance() {
        return OrderNoUtilsHolder.INSTANCE;
    }


    /**
     * 生成订单号（25位）：时间（精确到毫秒）+3位随机数+5位用户id
     */
    public synchronized String getOrderNo(Long userId) {
        //时间（精确到毫秒）
        DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String localDate = LocalDateTime.now().format(ofPattern);
        //3位随机数
        String randomNumeric = RandomStringUtils.randomNumeric(3);
        //5位用户id
        int subStrLength = 5;
        String sUserId = userId.toString();
        int length = sUserId.length();
        String str;
        if (length >= subStrLength) {
            str = sUserId.substring(length - subStrLength, length);
        } else {
            str = String.format("%0" + subStrLength + "d", userId);
        }
        String orderNum = localDate + randomNumeric + str;
        return orderNum;
    }

    public synchronized String getOrderNo(String prefix,Long userId) {
        //时间（精确到毫秒）
        DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String localDate = LocalDateTime.now().format(ofPattern);
        //3位随机数
        String randomNumeric = RandomStringUtils.randomNumeric(3);
        //5位用户id
        int subStrLength = 5;
        String sUserId = userId.toString();
        int length = sUserId.length();
        String str;
        if (length >= subStrLength) {
            str = sUserId.substring(length - subStrLength, length);
        } else {
            str = String.format("%0" + subStrLength + "d", userId);
        }
        String orderNum = prefix + localDate + randomNumeric + str;
        return orderNum;
    }

    public synchronized String getOrderNo() {
        //时间（精确到毫秒）
        DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String localDate = LocalDateTime.now().format(ofPattern);
        //3位随机数
        String randomNumeric = RandomStringUtils.randomNumeric(8);
        String orderNum = localDate + randomNumeric;
        return orderNum;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(getInstance().getOrderNo(RandomUtil.randomLong()));
            System.out.println(getInstance().getOrderNo("WQ",RandomUtil.randomLong()));
            System.out.println(getInstance().getOrderNo());
            System.out.println("-------------------------------------");
        }

    }
}
